﻿using Common;
using DadayunApi.Model;
using KbtSync.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KbtSync
{
    public partial class FrmSettings : Form
    {
        string settingFile="settings.ini";
        MyConfiguration cfg = new MyConfiguration(true);
        public FrmSettings()
        {
            InitializeComponent();
        }

        private void FrmSettings_Load(object sender, EventArgs e)
        {
            if (File.Exists(settingFile))
            {
                SqlConnectionStringBuilder builder = null;
                cfg.Load(settingFile);
                
                if (cfg.ContainsKey(SettingItems.erpDbConnString))
                {
                    string erpConnstring = cfg.ReadString(SettingItems.erpDbConnString);
                    if (!string.IsNullOrEmpty(erpConnstring))
                    {//如果有ERP设置，则用。没有则直接使用SCGL的
                        builder = new SqlConnectionStringBuilder(erpConnstring);
                        txtErpServer.Text = builder.DataSource;
                        txtDatabase.Text = builder.InitialCatalog;
                        txtDbUser.Text = builder.UserID;
                        txtDbPasswd.Text = builder.Password;
                    }
                }
                if (cfg.ContainsKey(SettingItems.ddyBaseUri)) txtBaseUri.Text = cfg.ReadString(SettingItems.ddyBaseUri);
                if (cfg.ContainsKey(SettingItems.ddyTenantName)) txtTenantName.Text = cfg.ReadString(SettingItems.ddyTenantName);
                if (cfg.ContainsKey(SettingItems.ddyUsername)) txtUserName.Text = cfg.ReadString(SettingItems.ddyUsername);
                if (cfg.ContainsKey(SettingItems.ddyPasswd)) txtPassword.Text = cfg.ReadString(SettingItems.ddyPasswd);
                if (cfg.ContainsKey(SettingItems.ddyAppKey)) txtAppKey.Text = cfg.ReadString(SettingItems.ddyAppKey);
                if (cfg.ContainsKey(SettingItems.ddySecret)) txtAppSecret.Text = cfg.ReadString(SettingItems.ddySecret);
                if (cfg.ContainsKey(SettingItems.ddyPubkey)) txtAppPubKey.Text = cfg.ReadString(SettingItems.ddyPubkey);
                if (cfg.ContainsKey(SettingItems.reportToEmail)) txtReportTo.Text = cfg.ReadString(SettingItems.reportToEmail);
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            bool ready=true;
            string msg = "";
            try
            {
                SunlikeDAL sunlikeDAL = new SunlikeDAL(BuildConnString());
                if (sunlikeDAL.DbReady())
                {
                    msg = "数据库配置成功!";

                }
                else
                {
                    ready = false;
                    msg = "数据库配置失败!";
                }
            }
            catch (Exception)
            {
                ready = false;
                msg = "数据库配置失败!";
            }
            try
            {
                AppAuthBase authBase = new AppAuthBase
                {
                    AppKey = txtAppKey.Text,
                    AppSecret = txtAppSecret.Text,
                    Password = txtPassword.Text,
                    PublicKey = txtAppPubKey.Text,
                    TenantName = txtTenantName.Text,
                    Username = txtUserName.Text
                };
                DadayunDAL dadayunDAL = new DadayunDAL(authBase, txtBaseUri.Text);
                if(dadayunDAL.GetServerTime()>DateTime.MinValue)
                {
                    msg += "\r\n配置搭搭云平台成功！";

                }
                else
                {
                    ready = false;
                    msg += "\r\n配置搭搭云平台失败！";
                }
            }
            catch (Exception)
            {
                ready = false;
                msg += "\r\n配置搭搭云平台失败！";
            }
            if(ready)
            {
                MessageBox.Show(msg,"配置测试成功！",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(msg,"配置测试失败！",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

        private string BuildConnString()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
            {
                DataSource = txtErpServer.Text,
                InitialCatalog = txtDatabase.Text,
                UserID = txtDbUser.Text,
                Password = txtDbPasswd.Text,
                MultipleActiveResultSets = true,
                ApplicationName = "Dadayun Sync"
            };
            builder.IntegratedSecurity = string.IsNullOrEmpty(builder.UserID) ? true : false;
            return builder.ConnectionString;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            
            string connString = BuildConnString();
            cfg.WriteString(SettingItems.erpDbConnString, connString);
            cfg.WriteString(SettingItems.ddyBaseUri, txtBaseUri.Text);
            cfg.WriteString(SettingItems.ddyTenantName, txtTenantName.Text);
            cfg.WriteString(SettingItems.ddyUsername, txtUserName.Text);
            cfg.WriteString(SettingItems.ddyPasswd, txtPassword.Text);
            cfg.WriteString(SettingItems.ddyAppKey, txtAppKey.Text);
            cfg.WriteString(SettingItems.ddySecret, txtAppSecret.Text);
            cfg.WriteString(SettingItems.ddyPubkey, txtAppPubKey.Text);
            cfg.WriteString(SettingItems.reportToEmail, txtReportTo.Text);
            cfg.Save(settingFile);
            DialogResult = DialogResult.OK;
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }

    internal class SettingItems
    {
        public static string erpDbConnString = "ErpDbConnString";
        public static string ddyBaseUri = "DdyBaseUri";
        public static string ddyTenantName = "DdyTenantName";
        public static string ddyUsername = "DdyUsername";
        public static string ddyPasswd = "DdyPasswd";
        public static string ddyAppKey = "DdyAppKey";
        public static string ddySecret = "DdySecret";
        public static string ddyPubkey = "DdyPubkey";
        public static string reportToEmail = "ReportToEmail";
    }
}
